<?php

namespace frontend\models;

use common\helps\tools;
use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;
use yii\db\Query;

/**
 * This is the model class for table "Information".
 *
 */
class Information extends ActiveRecord
{
    public $type;// 操作类型
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%information}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return[
            [['title','title','pic','info'], 'trim'],
            [['id','title','title','pic','info','status','is_recommend','mid'], 'required', 'message'=>'{attribute}不能为空'],
            [['id','type','status','is_recommend','mid','project_id'], 'match', 'pattern' => '/^[1-9][0-9]*$/','message'=>'{attribute}值无效'],
//            [['title','pic'], 'unique', 'message'=>'{attribute}已存在'],
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '资讯id',
            'title' => '标题',
            'mid'=>'分类id',
            'status'=>'资讯状态',
            'is_recommend'=>'是否推荐',
            'project_id'=>'绑定项目',
            'pic'=>'封面图',
            'info'=>'资讯详情',
            'type'=>'操作类型',
        ];
    }

    public function scenarios()
    {
        return [
            'default_create' => [
                'title',
                'mid',
                'status',
                'is_recommend',
                'pic',
                'info',
                'type',
                'project_id',
            ],
            'default_update' => [
                'id',
                'title',
                'mid',
                'status',
                'is_recommend',
                'pic',
                'info',
                'type',
                'project_id',
            ],
            'create' => [
                'title',
                'mid',
                'status',
                'is_recommend',
                'project_id',
                'user_id',
                'pic',
                'info',
                'created_at',
                'updated_at',
                'deleted_at'
            ],
            'update' => [
                'id',
                'title',
                'mid',
                'status',
                'is_recommend',
                'project_id',
                'user_id',
                'pic',
                'info',
                'created_at',
                'updated_at',
                'deleted_at'
            ],
        ];
    }



    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }


    /**
     * 获取资讯列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getInformationList($params){
        $condition=['information.deleted_at'=>null,'information.status'=>1,'information_class.status'=>1];
        if(!empty($params['mid'])){
            $condition['information.mid'] = intval($params['mid']);
        }
        if(!empty($params['is_recommend'])){
            $condition['information.is_recommend'] = intval($params['is_recommend']);
        }
        $list = (new Query())
            ->select('information.id,information.title as name,information.info,information.pic,information.describe,information.click_num,information_class.title as class_name,information_class.id as mid,information.is_recommend,information.status,FROM_UNIXTIME(information.created_at) as time')
            ->from('information')
            ->innerJoin('information_class','information_class.id=information.mid')
            ->where($condition)
            ->orderBy('information.id desc')
            ->all();

        return empty($list)?array():$list;

    }


    /**
     * 获取首页资讯列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getIndexInformationList($params){
        $condition=['information.deleted_at'=>null,'information.status'=>1,'information_class.status'=>1];
        if(!empty($params['mid'])){
            $condition['information.mid'] = intval($params['mid']);
        }
        if(!empty($params['is_recommend'])){
            $condition['information.is_recommend'] = intval($params['is_recommend']);
        }
        $list = (new Query())
            ->select('information.id,information.mid,information.title as name,information.info,information.pic,information.describe,information.click_num,information_class.title as class_name,information.is_recommend,information.status,FROM_UNIXTIME(information.created_at) as time')
            ->from('information')
            ->innerJoin('information_class','information_class.id=information.mid')
            ->where($condition)
            ->groupBy('information.mid')
            ->orderBy('information.id desc')
            ->all();

        return empty($list)?array():$list;

    }





    /**
     * 获取资讯详情
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getInformationInfo($params){
        $condition=['information.deleted_at'=>null,'information.status'=>1,'information.id'=>intval($params['id'])];
        if(!empty($params['mid'])){
            $condition['information.mid'] = intval($params['mid']);
        }
        if(!empty($params['is_recommend'])){
            $condition['information.is_recommend'] = intval($params['is_recommend']);
        }
        $list = (new Query())
            ->select('information.id,information.title as name,information.click_num,information.info,information.pic,information_class.title as class_name,information_class.id as mid,information.is_recommend,information.status,FROM_UNIXTIME(information.created_at) as time')
            ->from('information')
            ->leftJoin('information_class','information_class.id=information.mid')
            ->where($condition)
            ->one();
        $recommend_information=[];
        $all_list = $this->find()->where(['and',['<>','id',intval($params['id'])],['deleted_at'=>null,'status'=>1]])->asArray()->all();
        if(count($all_list)){
            $key=array_rand($all_list);
            $recommend_information=$all_list[$key];
        }
        $list['recommend_information'] =$recommend_information ;
        static::updateAllCounters(['click_num' => 1], ['id' =>intval($params['id'])]); //自增查看数量
        return empty($list)?array():$list;

    }



    /**
     * 新增与编辑资讯
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function editInformation($param){
        if($param['type']>1){ //编辑
            $model = static::findOne(['id' =>$param['id']]);
            if(empty($model)) return array('error'=>'未查询到角色信息');
            $model->scenario = 'update';
        }else{
            $model = new self();
            $model->scenario = 'create';
        }
        unset($param['id']);
        $model->setAttributes($param, false);
        if (!$model->save()) {
            return array('error'=>'操作失败');
        }else{
            return array('error'=>'');
        }
    }


}
